using System;
using System.Collections.Generic;
using Voodoo.Sauce.Internal;

namespace Voodoo.Sauce.Common.Utils
{
	public class HandledAction<T>
	{
		private readonly List<Action<T>> _actions = new List<Action<T>>();

		private readonly string _tag;

		public HandledAction(string tag)
		{
			_tag = tag;
		}

		public void Invoke(T t)
		{
			Action<T>[] array = _actions.ToArray();
			foreach (Action<T> action in array)
			{
				try
				{
					action(t);
				}
				catch (Exception arg)
				{
					VoodooLog.LogWarning(Module.COMMON, _tag, $"Exception caught: {arg}");
				}
			}
		}

		public void Add(Action<T> action)
		{
			if (!_actions.Contains(action))
			{
				_actions.Add(action);
			}
		}

		public void Remove(Action<T> action)
		{
			if (_actions.Contains(action))
			{
				_actions.Remove(action);
			}
		}

		public void Clear()
		{
			_actions.RemoveAll((Action<T> a) => true);
		}
	}
}
